import socket,copy
from sys import path
path.append("..")
from xmlrpc import client
from time import sleep
from random import random
from utils import Utilities
from threading import Thread, get_native_id

class RecordsTree():
	leaves = {}
	def __init__(self,fileToImport=None):
		self.leaves = {}
		if(fileToImport==None):
			pass
		else:
			# irohia,1000,2000,3000,4000,5000,6000
			# irohia,1000,2000,3000,4000,5000,6000
			# irohia,1000,2000,3000,4000,5000,6000
			# irohia,1000,2000,3000,4000,5000,6000
			#
			# import the file here, it looks like the comments up above
			pass
	def addRecord(self,recStr):
		try:
			compares = []
			uname = recStr.split(",")[0]
			times = recStr.split(",")[1:]
			for i in range(len(times)):
				self.leaves[uname][i] = (int(times[i]) if int(times[i])<=int(self.leaves[uname][i]) else int(self.leaves[uname][i]))
			for i in range(len(self.leaves[recStr.split(",")[0]])):
				if(self.leaves[uname][i] == int(times[i])):
					compares.append(True)
				else:
					compares.append(False)
			return(compares)
		except Exception as e:
			uname = recStr.split(",")[0]
			times = recStr.split(",")[1:]
			self.leaves[uname] = []
			for i in range(len(times)):
				self.leaves[uname].append(int(times[i]))
			return(True)
	def __repr__(self):
		reprStr = ""
		for k,v in zip(self.leaves.keys(),self.leaves.values()):
			reprStr=reprStr+k+","
			for i in v:
				reprStr=reprStr+str(i)+","
			reprStr = reprStr[:len(reprStr)-1]
			reprStr=reprStr+"\n"
		reprStr = reprStr[:len(reprStr)-1]
		return(reprStr)

class Sectorum():
	def exec(self,u,prefix,sock):
		t = Thread(target=self.loop,args=(u,prefix,sock),daemon=True)
		t.start()
	def loop(self,u,prefix,sock):
		u.sendMessage(client.dumps(("Sectorum is starting...",),methodname="ChatSend").encode(),sock)
		secRecs = RecordsTree()
		recStr = ""
		u.registerListener(get_native_id())
		while(1):
			try:
				data,method = u.listen(get_native_id())
			except Exception as e:
				if(str(e)=="cannot unpack non-iterable NoneType object"):
					pass
				else:
					print(e)
				continue
			if(method == "TrackMania.PlayerCheckpoint"):
				userName,time,cpIndex = data[1],data[2],data[4]
				if(int(time) == 0):
					continue
				if(recStr==""):
					recStr = recStr+userName+","
				recStr = recStr+str(time)+","
			if(method == "TrackMania.PlayerFinish"):
				userName,time = data[1],data[2]
				if(time!=0):
					recStr = recStr[:len(recStr)-1]
					compares = secRecs.addRecord(recStr)
					recStr = ""
					try:
						u.sendMessage(client.dumps(("Sector records:",userName),methodname="ChatSendToLogin").encode(),sock)
						for i in range(len(secRecs.leaves[userName])):
							u.sendMessage(client.dumps(("CP[%s]#%s: %s"%(("^" if compares[i]==True else "v"),str(i+1),u.msToHMS(secRecs.leaves[userName][i])),userName),methodname="ChatSendToLogin").encode(),sock)
						u.sendMessage(client.dumps(("Legend: ^ = Beat record | v = Didn't beat record",userName),methodname="ChatSendToLogin").encode(),sock)
					except Exception as e:
						u.sendMessage(client.dumps(("You set your first set of sector records on this track, for this round!",userName),methodname="ChatSendToLogin").encode(),sock)
						for i in range(len(secRecs.leaves[userName])):
							u.sendMessage(client.dumps(("CP#%s: %s"%(str(i+1),u.msToHMS(secRecs.leaves[userName][i])),userName),methodname="ChatSendToLogin").encode(),sock)
				else:
					pass
			if(method == "TrackMania.PlayerChat"):
				user, command, args = u.splitData(data,method)
				if(command == prefix+"sr"):
					minList = []
					for k,v in zip(secRecs.leaves.keys(), secRecs.leaves.values()):
						for k1 in secRecs.leaves[k]:
							if(minList==[]):
								for k2 in secRecs.leaves[k]:
									minList.append(k2)
								break
							else:
								for v1 in range(len(maxList)):
									minList[v1] = min(k1,minList[v1])
					for i in range(len(minList)):
						u.sendMessage(client.dumps(("CP#%s: %s"%(str(i+1),u.msToHMS(minList[i])),user),methodname="ChatSendToLogin").encode(),sock)